<?php

namespace app\admin\controller;

use app\common\model\ConfigPriModel;
use app\common\model\ConfigPubModel;
use app\common\model\ConfigPubSemModel;
use app\common\model\ConfigPubSemWebModel;
use app\common\model\ConfigPubSpecModel;
use app\common\model\ConfigPubJoycircleModel;
use app\common\model\ConfigTagModel;
use app\common\model\RegSourceModel;
use app\common\model\ConfigSourceModel;
use think\facade\Request;

class SettingController extends BaseController
{
    /**
     * 私密配置
     * @return mixed
     */
    public function indexpri()
    {
        return $this->assign(
            [
                'config_pri' => ConfigPriModel::get(1),
                'type' => Request::param('type', 1)
            ]
        )->fetch();
    }

    /**
     * 直播配置
     * @return mixed
     */
    public function indexlive()
    {
        return $this->assign(
            [
                'config_pri' => ConfigPriModel::get(1),
                'type' => Request::param('type', 1)
            ]
        )->fetch();
    }

    /**
     * 公共配置
     * @return mixed
     */
    public function indexpb()
    {
        $all_param = Request::param();
        $source_key = isset($all_param['source_key']) ? $all_param['source_key'] : '';
        $config = null;
        if ($all_param && $source_key) {
            if ($source_key == 'pub') {
                $config = ConfigPubModel::get(1);
            }else{
                $config = ConfigSourceModel::where('source_key', $all_param['source_key'])->findOrEmpty();
            }
        } else{
            $config = ConfigPubModel::get(1);
        }
        return $this->assign(
            [
                'config_pub' => $config,
                'type' => Request::param('type', 1),
                'source_key' => Request::param('source_key',  $source_key)
            ]
        )->fetch();
    }

    public function index()
    {
        return $this->assign([])->fetch();
    }

    public function source()
    {
        $sources = $this->get_config_sources();
        return $this->assign(
            [
                'sources' => $sources,
                'first_source_key' => isset($sources[0]) ? $sources[0]->source_key : '',
            ]
        )->fetch();
    }

    public function get_config_sources()
    {
        $configs = ConfigSourceModel::all();
        $sources = RegSourceModel::all();
        $cfg_srcs = [];
        foreach ($configs as $item) {
            foreach ($sources as $item2) {
                if ($item->source_key == $item2->source_key) {
                    $source = new \stdClass();
                    $source->source_name = $item2->source_name;
                    $source->source_key = $item2->source_key;
                    $cfg_srcs[] = $source; 
                    break;
                }
            }
        }

        // 对 cfg_srcs 数组按照 source_name 排序
        usort($cfg_srcs, function($a, $b) {
            return strcmp($a->source_name, $b->source_name);
        });

        // 将元素 pub 添加到数组的第一个位置
        $pub = new \stdClass();
        $pub->source_name = '公共配置';
        $pub->source_key = 'pub';
        array_unshift($cfg_srcs, $pub);
        return $cfg_srcs;
    }

    public function source_config_add() {
        $sources = RegSourceModel::alias('rs')
        ->leftJoin('db_config_source cs', 'rs.source_key = cs.source_key')
        ->whereNull('cs.source_key')
        ->field('rs.*')
        ->select();
        return $this->assign([
            'sources' => $sources,
        ])->fetch();
    }

    public function source_config_del() {
        $param = Request::param();
        if (!isset($param['sourceKey'])) {
            return self::bulidFail('参数错误');
        }
        if ($param['sourceKey'] == 'pub') {
            return self::bulidFail('不能删除公共配置');
        }
        $config_source = ConfigSourceModel::where("source_key",$param['sourceKey'])->find();
        if ($config_source) {
            if ($config_source->delete()) {
                return self::bulidSuccess();
            }
        }
        return self::bulidFail();
    }

    public function index_sem()
    {
        return $this->assign(
            [
                'config_pub' => ConfigPubSemModel::get(1),
                'type' => Request::param('type', 1)
            ]
        )->fetch();
    }

    public function index_sem_web()
    {
        return $this->assign(
            [
                'config_pub' => ConfigPubSemWebModel::get(1),
                'type' => Request::param('type', 1)
            ]
        )->fetch();
    }

    public function index_spec()
    {
        return $this->assign(
            [
                'config_pub' => ConfigPubSpecModel::get(1),
                'type' => Request::param('type', 1)
            ]
        )->fetch();
    }

    public function index_joycircle()
    {
        return $this->assign(
            [
                'config_pub' => ConfigPubJoycircleModel::get(1),
                'type' => Request::param('type', 1)
            ]
        )->fetch();
    }

    /**
     * 标签配置
     * @return mixed
     */
    public function tag()
    {
        return $this->fetch();
    }

    public function add_tag()
    {
        return $this->fetch();
    }

    public function edit_tag()
    {
        return $this->assign(['taginfo' => ConfigTagModel::get(Request::param("id"))])->fetch();
    }

    public function savepri()
    {
        $param = Request::param();
        if (isset($param['baseheats_start']) && isset($param['baseheats_end'])) {
            if ($param['baseheats_start'] > $param['baseheats_end']) {
                return self::bulidFail('基础热度范围填写错误');
            }
        }
        $config_pri = ConfigPriModel::get(1);
        if ($config_pri->save($param)) {
            redis_del('go_webapi_ConfigPri');

            if (isset($param['edit_type']) && $param['edit_type'] == 'live') {
                $log_content = "修改直播配置";
            } else {
                $log_content = "修改私密配置";
            }
            $this->addAdminLog($log_content);

            return self::bulidSuccess([$config_pri]);
        }
        return self::bulidFail();
    }

    public function savepub()
    {
        $param = Request::param();
        if (!isset($param['source_key'])) {
            if (isset($param['edit_type']) && $param['edit_type'] == 'live') {
                $param['source_key'] = 'pub';
            }else {
                return self::bulidFail();
            }
        }
        $source_key = $param['source_key'];
        if ($param && $source_key) {
            if ($source_key == 'pub') {
                $config_pub = ConfigPubModel::get(1);
                $config_pub->source_key = 'pub';
            }else{
                ConfigSourceModel::startTrans();
                try {
                    $config_pub = ConfigSourceModel::where('source_key', $param['source_key'])->lock(true)->find();
                    if (!$config_pub) {
                        $config_pub = new ConfigSourceModel($param);
                        $config_pub->is_new = true;
                    }
                    ConfigSourceModel::commit();
                }catch (\Exception $e){
                    ConfigSourceModel::rollback();
                    return self::bulidFail();
                }
            }
        } else {
            return self::bulidFail();
        }
        if (isset($param['type_flag']) && $param['type_flag'] == 1) {
            if (!empty($param['quiz_factor']) && is_array($param['quiz_factor'])) {
                $param['quiz_factor'] = array_sum($param['quiz_factor']);
            } else {
                $param['quiz_factor'] = 0;
            }

            if (!empty($param['video_switch']) && is_array($param['video_switch'])) {
                $param['video_switch'] = array_sum($param['video_switch']);
            } else {
                $param['video_switch'] = 0;
            }

            if (!empty($param['live_preview_switch']) && is_array($param['live_preview_switch'])) {
                $param['live_preview_switch'] = array_sum($param['live_preview_switch']);
            } else {
                $param['live_preview_switch'] = 0;
            }
        }

        if ($config_pub->save($param)) {
            redis_del('go_webapi_ConfigPub');
            redis_del('go_webapi_ConfigSource');
            redis_del('SOURCE_CONFIG_KEY');

            if (isset($param['edit_type']) && $param['edit_type'] == 'live') {
                $log_content = "修改直播配置";
            } else if ((isset($param['source_key']) && $param['source_key'] != 'pub')) {
                $log_content = "修改渠道配置";
            } else {
                $log_content = "修改公共配置";
            }
            parent::addAdminLog($log_content);

            return self::bulidSuccess([$config_pub]);
        }
        return self::bulidDataFail($config_pub);
    }

    public function savepub_sem()
    {
        $param = Request::param();
        $config_pub = ConfigPubSemModel::get(1);
        if (isset($param['type_flag']) && $param['type_flag'] == 1) {
            if (!empty($param['quiz_factor']) && is_array($param['quiz_factor'])) {
                $param['quiz_factor'] = array_sum($param['quiz_factor']);
            } else {
                $param['quiz_factor'] = 0;
            }

            if (!empty($param['video_switch']) && is_array($param['video_switch'])) {
                $param['video_switch'] = array_sum($param['video_switch']);
            } else {
                $param['video_switch'] = 0;
            }

            if (!empty($param['live_preview_switch']) && is_array($param['live_preview_switch'])) {
                $param['live_preview_switch'] = array_sum($param['live_preview_switch']);
            } else {
                $param['live_preview_switch'] = 0;
            }
        }

        if ($config_pub->save($param)) {

            if (isset($param['edit_type']) && $param['edit_type'] == 'live') {
                $log_content = "修改直播配置";
            } else {
                $log_content = "修改公共配置";
            }
            parent::addAdminLog($log_content);

            return self::bulidSuccess([$config_pub]);
        }
        return self::bulidDataFail($config_pub);
    }

    public function savepub_sem_web()
    {
        $param = Request::param();
        $config_pub = ConfigPubSemWebModel::get(1);
        if (isset($param['type_flag']) && $param['type_flag'] == 1) {
            if (!empty($param['quiz_factor']) && is_array($param['quiz_factor'])) {
                $param['quiz_factor'] = array_sum($param['quiz_factor']);
            } else {
                $param['quiz_factor'] = 0;
            }

            if (!empty($param['video_switch']) && is_array($param['video_switch'])) {
                $param['video_switch'] = array_sum($param['video_switch']);
            } else {
                $param['video_switch'] = 0;
            }

            if (!empty($param['live_preview_switch']) && is_array($param['live_preview_switch'])) {
                $param['live_preview_switch'] = array_sum($param['live_preview_switch']);
            } else {
                $param['live_preview_switch'] = 0;
            }
        }

        if ($config_pub->save($param)) {

            if (isset($param['edit_type']) && $param['edit_type'] == 'live') {
                $log_content = "修改直播配置";
            } else {
                $log_content = "修改公共配置";
            }
            parent::addAdminLog($log_content);

            return self::bulidSuccess([$config_pub]);
        }
        return self::bulidDataFail($config_pub);
    }

    public function savepub_spec()
    {
        $param = Request::param();
        $config_pub = ConfigPubSpecModel::get(1);
        if (isset($param['type_flag']) && $param['type_flag'] == 1) {
            if (!empty($param['quiz_factor']) && is_array($param['quiz_factor'])) {
                $param['quiz_factor'] = array_sum($param['quiz_factor']);
            } else {
                $param['quiz_factor'] = 0;
            }

            if (!empty($param['video_switch']) && is_array($param['video_switch'])) {
                $param['video_switch'] = array_sum($param['video_switch']);
            } else {
                $param['video_switch'] = 0;
            }

            if (!empty($param['live_preview_switch']) && is_array($param['live_preview_switch'])) {
                $param['live_preview_switch'] = array_sum($param['live_preview_switch']);
            } else {
                $param['live_preview_switch'] = 0;
            }
        }

        if ($config_pub->save($param)) {
            redis_del('go_webapi_ConfigPubSpec');
            if (isset($param['edit_type']) && $param['edit_type'] == 'live') {
                $log_content = "修改直播配置";
            } else {
                $log_content = "修改公共配置";
            }
            parent::addAdminLog($log_content);

            return self::bulidSuccess([$config_pub]);
        }
        return self::bulidDataFail($config_pub);
    }

    public function savepub_joycircle()
    {
        $param = Request::param();
        $config_pub = ConfigPubJoycircleModel::get(1);
        if (isset($param['type_flag']) && $param['type_flag'] == 1) {
            if (!empty($param['quiz_factor']) && is_array($param['quiz_factor'])) {
                $param['quiz_factor'] = array_sum($param['quiz_factor']);
            } else {
                $param['quiz_factor'] = 0;
            }

            if (!empty($param['video_switch']) && is_array($param['video_switch'])) {
                $param['video_switch'] = array_sum($param['video_switch']);
            } else {
                $param['video_switch'] = 0;
            }

            if (!empty($param['live_preview_switch']) && is_array($param['live_preview_switch'])) {
                $param['live_preview_switch'] = array_sum($param['live_preview_switch']);
            } else {
                $param['live_preview_switch'] = 0;
            }
        }

        if ($config_pub->save($param)) {
            redis_del('go_webapi_ConfigPubJoycircle');
            if (isset($param['edit_type']) && $param['edit_type'] == 'live') {
                $log_content = "修改直播配置";
            } else {
                $log_content = "修改公共配置";
            }
            parent::addAdminLog($log_content);

            return self::bulidSuccess([$config_pub]);
        }
        return self::bulidDataFail($config_pub);
    }

    public function gettags()
    {
        return self::bulidSuccess(ConfigTagModel::all());
    }

    public function add_tag_post()
    {
        $data = Request::param();
        $data['title'] = trim($data['title']);
        if (!$data['title']) {
            return static::bulidFail('请输入标题');
        }

        if (!is_numeric($data['point']) || $data['point'] < 0) {
            return static::bulidFail('热度值错误, 请输入纯数字');
        }

        if (mb_strlen($data['title']) > 30) {
            return static::bulidFail('标签名不能超过30个字符');
        }

        $tagModel = new ConfigTagModel(array_merge($data, ['operator' => $this->admin_name]));
        if ($tagModel->save()) {
            //操作日志
            $log_content = "添加标签配置，ID：{$tagModel->id}，标题：{$tagModel->title}";
            parent::addAdminLog($log_content);
            return self::bulidSuccess([]);
        }
        return self::bulidFail();
    }

    public function edit_tag_post()
    {
        $data = Request::param();
        if (!$data['title']) {
            return static::bulidFail('请输入标题');
        }

        if (!is_numeric($data['point']) || $data['point'] < 0) {
            return static::bulidFail('热度值错误, 请输入纯数字');
        }

        if (mb_strlen($data['title']) > 30) {
            return static::bulidFail('标签名不能超过30个字符');
        }

        $tagModel = ConfigTagModel::get(Request::param("id"));
        if ($tagModel->save(array_merge($data, ['operator' => $this->admin_name]))) {
            //操作日志
            $log_content = "编辑标签配置，ID：{$tagModel->id}，标题：{$tagModel->title}";
            parent::addAdminLog($log_content);
            return self::bulidSuccess([]);
        }
        return self::bulidFail();
    }

    public function del_tag_post()
    {
        if (!($id = trim($this->post('id', ''))) || !is_numeric($id)) {
            return static::bulidFail();
        }

        if (!$model = ConfigTagModel::where('id', $id)->find()) {
            return static::bulidFail();
        }

        if (!$model->delete()) {
            return static::bulidFail();
        }
        //操作日志
        $log_content = "删除标签配置，ID：{$model->id}，标题：{$model->title}";
        parent::addAdminLog($log_content);

        return static::bulidSuccess();
    }
}
